﻿using FytSoa.Application.Car;
using FytSoa.Application.Shop;
using FytSoa.Application.Sys;
using FytSoa.Common.Enum;
using FytSoa.Common.Utils;
using FytSoa.Domain.Car;
using FytSoa.Domain.Cms;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using FytSoa.Domain.Shop;
using FytSoa.Domain.Sys;
using FytSoa.Domain.User;
using FytSoa.Sugar;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.App;
[ApiExplorerSettings(GroupName = "v5")]
public class AppIndexService: IApplicationService
{
    private readonly IMapper _mapper;
    private readonly ShopPointsOrderService _orderService;
    private readonly ShopPointsLogService _logService;
    private readonly SugarRepository<SysMessage> _thisRepository;
    public AppIndexService(IMapper mapper
    ,ShopPointsOrderService orderService
    ,ShopPointsLogService logService
    ,SugarRepository<SysMessage> thisRepository)
    {
        _mapper = mapper;
        _orderService = orderService;
        _logService = logService;
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 更新用户积分
    /// </summary>
    /// <returns></returns>
    public async Task<int> GetUserPointAsync(long id)
    {
        var userRepository = _thisRepository.ChangeRepository<SugarRepository<Member>>();
        var model = await userRepository.GetByIdAsync(id);
        return model.Point;
    }

    /// <summary>
    /// 获得积分商品列表
    /// </summary>
    /// <returns></returns>
    public async Task<PageResult<ShopPointsGoodsDto>> GetPointListAsync(PageParam param)
    {
        var pointRepository = _thisRepository.ChangeRepository<SugarRepository<ShopPointsGoods>>();
        var where = Expressionable.Create<ShopPointsGoods>();
        where.And(m => m.Status);
        var (list,totalItems,totalPage) = await pointRepository.GetPageResultAsync(where.ToExpression(), param.Page, param.Limit, m => m.Id);
        return new PageResult<ShopPointsGoodsDto>()
        {
            Items = _mapper.Map<List<ShopPointsGoodsDto>>(list),
            TotalItems = totalItems,
            TotalPages = totalPage
        };
    }

    /// <summary>
    /// 获得积分商品列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ShopPointsGoodsDto> GetPointAsync(long id)
    {
        var pointRepository = _thisRepository.ChangeRepository<SugarRepository<ShopPointsGoods>>();
        return _mapper.Map<ShopPointsGoodsDto>(await pointRepository.GetByIdAsync(id));
    }
    
    /// <summary>
    /// 获得积分记录
    /// </summary>
    /// <returns></returns>
    public async Task<PageResult<ShopPointsLogDto>> GetPointLogAsync(PageParam param)=>
        await _logService.GetPagesAsync(param);

    /// <summary>
    /// 获得个人的积分总数
    /// </summary>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<AppPointTotalDto> GetPointTotalAsync(long id)
    {
        var pointRepository = _thisRepository.ChangeRepository<SugarRepository<ShopPointsLog>>();
        return new AppPointTotalDto()
        {
            InTotal = await pointRepository.SumAsync(m => m.UserId==id && m.Flag == 1,m=>m.Point),
            OutTotal = await pointRepository.SumAsync(m => m.UserId==id && m.Flag ==2,m=>m.Point)
        };
    }

    /// <summary>
    /// 添加订单
    /// </summary>
    /// <returns></returns>
    public async Task<bool> AddPointOrderAsync(ShopPointsOrderDto model)
    {
        var pointRepository = _thisRepository.ChangeRepository<SugarRepository<ShopPointsOrder>>();
        model.Id = Unique.Id();
        
        //添加积分消费
        await _logService.AddAsync(new ShopPointsLogDto()
        {
            UserId = model.UserId,
            Flag = 2,
            GetType = ShopPointLogEnum.BuyProduct,
            Point = model.Point*model.Count
        });
        
        return await pointRepository.InsertAsync(_mapper.Map<ShopPointsOrder>(model));
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ShopPointsOrderDto>> GetOrderListAsync(PageParam param)=>
        await _orderService.GetPagesAsync(param);

    /// <summary>
    /// 抽奖信息
    /// </summary>
    /// <returns></returns>
    public async Task<CarsPrizeDto> GetPrizeAsync()
    {
        var prizeRepository = _thisRepository.ChangeRepository<SugarRepository<CarsPrize>>();
        var model = await prizeRepository.GetFirstAsync(m=>m.Status);
        return _mapper.Map<CarsPrizeDto>(model);
    }

    /// <summary>
    /// 返回预约车型信息及广告位图
    /// </summary>
    /// <returns></returns>
    public async Task<AppPrizeAdvDto> GetReserveAsync()
    {
        var advRepository = _thisRepository.ChangeRepository<SugarRepository<SysAdvInfo>>();
        var adv = await advRepository.GetFirstAsync(m => m.ColumnId ==1509706399330996224);
        var codeRepository = _thisRepository.ChangeRepository<SugarRepository<SysCode>>();
        var carType = await codeRepository.GetListAsync(m => m.TypeId == 1506527460819341312);
        return new AppPrizeAdvDto()
        {
            AdvInfo = _mapper.Map<SysAdvInfoDto>(adv),
            Codes = _mapper.Map<List<SysCodeDto>>(carType)
        };
    }

    /// <summary>
    /// 添加预约试驾信息
    /// </summary>
    /// <returns></returns>
    public async Task<bool> AddReserveAsync(CarsReserveDto model)
    {
        var reserveRepository = _thisRepository.ChangeRepository<SugarRepository<CarsReserve>>();
        return await reserveRepository.InsertAsync(_mapper.Map<CarsReserve>(model));
    }
    
    /// <summary>
    /// app反馈意见上报
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<bool> AddFackBack(AppFackBackParam param)
    {
        var userRepository = _thisRepository.ChangeRepository<SugarRepository<Member>>();
        var model = _mapper.Map<SysMessage>(param);
        model.Id = Unique.Id();
        var user = await userRepository.GetByIdAsync(param.UserId);
        if (user == null) return await _thisRepository.InsertAsync(model);
        model.UserName = user.NickName;
        model.Mobile = user.Mobile;
        return await _thisRepository.InsertAsync(model);
    }

    /// <summary>
    /// 替换程序Urls
    /// </summary>
    /// <param name="sourUrl"></param>
    /// <param name="newUrl"></param>
    /// <returns></returns>
    public async Task GetRepUrl(string sourUrl,string newUrl)
    {
        //栏目
        var columnRepository = _thisRepository.ChangeRepository<SugarRepository<CmsColumn>>();
        var columnList = await columnRepository.GetListAsync();
        foreach (var item in columnList)
        {
            if (!string.IsNullOrEmpty(item.ImgUrl))
            {
                item.ImgUrl = item.ImgUrl.Replace(sourUrl, newUrl);
            }

            if (!string.IsNullOrEmpty(item.Content))
            {
                item.Content=item.Content.Replace(sourUrl, newUrl);
            }
        }

        await columnRepository.UpdateRangeAsync(columnList);
        //文章
        var articleRepository = _thisRepository.ChangeRepository<SugarRepository<CmsArticle>>();
        var articleList = await articleRepository.GetListAsync();
        foreach (var item in articleList)
        {
            if (!string.IsNullOrEmpty(item.ImgUrl))
            {
                item.ImgUrl = item.ImgUrl.Replace(sourUrl, newUrl);
            }

            if (!string.IsNullOrEmpty(item.Content))
            {
                item.Content=item.Content.Replace(sourUrl, newUrl);
            }
        }

        await articleRepository.UpdateRangeAsync(articleList);
        //广告
        var advRepository = _thisRepository.ChangeRepository<SugarRepository<SysAdvInfo>>();
        var advList = await advRepository.GetListAsync();
        foreach (var item in advList)
        {
            if (!string.IsNullOrEmpty(item.ImgUrl))
            {
                item.ImgUrl = item.ImgUrl.Replace(sourUrl, newUrl);
            }
        }

        await advRepository.UpdateRangeAsync(advList);
        //商城
        var shopRepository = _thisRepository.ChangeRepository<SugarRepository<ShopPointsGoods>>();
        var shopList = await shopRepository.GetListAsync();
        foreach (var item in shopList)
        {
            if (!string.IsNullOrEmpty(item.ImgUrls))
            {
                item.ImgUrls = item.ImgUrls.Replace(sourUrl, newUrl);
            }

            if (!string.IsNullOrEmpty(item.Details))
            {
                item.Details=item.Details.Replace(sourUrl, newUrl);
            }
        }
        await shopRepository.UpdateRangeAsync(shopList);
    }
}